package user;

import utils.JsonOut;
import utils.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "ChangePasswordServlet")
public class ChangePasswordServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String email = UserSession.getUserSessionEmail(session);
        PrintWriter out = response.getWriter();
        if (email == null || email.isEmpty()){
            out.println(JsonOut.error(220, "not_login"));
            return;
        }

        String oldPass = request.getParameter("old_pass");
        String newPass = request.getParameter("new_pass");
        String newPassAgain = request.getParameter("new_pass_again");

        // 判断字段为空
        if (oldPass == null || oldPass.isEmpty()){
            out.println(JsonOut.error(201, "psw_empty"));
            return;
        }
        if (newPass == null || newPass.isEmpty()){
            out.println(JsonOut.error(201, "pass_empty"));
            return;
        }
        if (newPassAgain == null || newPassAgain.isEmpty()){
            out.println(JsonOut.error(201, "pass_empty"));
            return;
        }


        String savedPass = (new MysqlUtils()).getPassword(email);
        if (savedPass == null){
            out.println(JsonOut.error(101, "not_exist"));
            return;
        }

        // 检查原密码
        if (!(new MysqlUtils()).checkPassword(oldPass, savedPass)){
            out.println(JsonOut.error(102, "psw_error"));
            return;
        }

        // 检查新密码长度
        if (newPass.length() < 6){
            out.println(JsonOut.error(112, "psw_too_short"));
            return;
        }

        // 检查两次新密码是否一致
        if (!newPass.equals(newPassAgain)){
            out.println(JsonOut.error(103, "pass_incorrect"));
            return;
        }

        if (!(new MysqlUtils()).userChangePassword(email, newPass)){
            out.println(JsonOut.error(500, "sql_sth_wrong"));
            return;
        }

        out.println(JsonOut.error(0, "password_changed"));

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(JsonOut.error(403, "forbidden"));
    }
}
